package com.example.springbootpro.config;

import com.example.springbootpro.exception.BusinessException;
import com.example.springbootpro.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理数据不存在异常（EmptyResultDataAccessException）
     */
    @ExceptionHandler(EmptyResultDataAccessException.class)
    public Result handleEmptyResult(EmptyResultDataAccessException e) {
        log.error("数据查询失败：预期返回1条数据，但实际返回0条", e);
        return  Result.error("404", "数据不存在");
    }

    /**
     * 处理业务异常（BusinessException）
     */
    @ExceptionHandler(BusinessException.class)
    public  Result handleBusinessException(BusinessException e) {
        log.error("业务异常：code={}, message={}", e.getCode(), e.getMessage(), e);
        return  Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理其他未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常："+e.toString());
        e.printStackTrace();
        System.out.println(e instanceof BusinessException);
         return  Result.error("500",e.getMessage());
    }
}